#!/usr/bin/env perl

BEGIN {
	push @::INC,".." if -f "../pv3.pm";
	push @::INC,$::ENV{CODEMGR_LIBS} if exists($::ENV{CODEMGR_LIBS});
}

use pv3;
use Getopt::Long;
use Config;
use strict;

$::ARG_pv=undef;
$::ARG_force=0;

sub usage {
	print "
Usage: pv3_unlock [-p file] [-f] file ...

The pv3_unlock allows a new file to be initiated as the first
version under PV3 code control, or allows an existing checked out
file to be checked back in again.

It supports the following command line arguments:

-p   Indicates the alternative file wherer the PV3 version
     information relevant to the current directory is being stored. 
-f   Force the unlock even if you did not check out the file.

Written by Simon Edwards, (C) 2006-2010 www.advantsys.co.uk
";
	exit 1;
}

if(!GetOptions(
	"pv=s"		=> \$::ARG_pv,
	"force"		=> \$::ARG_force,
	)) {
	usage;
}

if(defined($::ARG_pv)) {
	if(! -d dirname($::ARG_pv)) {
		mkdir dirname($::ARG_pv),0775 or die("Failed to create directory $::ARG_pv: $!");
	}
}
my %args=();
$args{COMMENT}=$::ARG_msg;
$args{FORCE}=1 if $::ARG_force;

@::UNLOCK_LIST=();

if($Config{osname} =~ /mswin/i) {
	my @F=();
	for my $cpat (@ARGV) {
		push @F,glob($cpat);
	}
	@ARGV=@F;
}

for my $cfile (@ARGV) {
# Check in a file - either new file [no ,pv] or checked [out]

	next if -d $cfile;
	next if $cfile =~ /,pv3$/;
	if(! -f $cfile) {
		print "ERROR: File '$cfile' does not exist - ignoring.\n";
		next;
	}
	push @::UNLOCK_LIST,$cfile;
}

{
	$args{PVFILE}=$::ARG_pv if defined($::ARG_pv);
	my $fails=0; my $ok=0;
	my $newlist;
	my $res=pv3::unlock(FILE => [@::UNLOCK_LIST],%args);
	for my $cres (@$res) {
		my @R=(@$cres);
		if($R[0]==-1) {
			$fails++;
			if(@R==3 && defined($R[2]) && length($R[2])) {
				print "ERROR : $R[2] - $R[1].\n";
			} else {
				print "ERROR : $R[1]\n";
			}
		}
		if($R[0]==-2) {
			print "WARN  : $R[2] - $R[1].\n";
		}
		if($R[0]==0) {
			$ok++;
			print "UNLOCK: $R[5] - $R[2]\[$R[1]\] - $R[3]\n";
		}
	}
	exit(0) if $fails==0;
	exit(1);
}

